<?php

namespace App\Listeners;

use App\Events\ClickLogEvent;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Cache;
use App\Models\StatisticDetail;
use Illuminate\Support\Facades\Log;

class Statistics implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\ClickLogEvent  $event
     * @return void
     */
    public function handle(ClickLogEvent $event)
    {
        $clickLog = $event->clickLog;

        $statistics_date = $clickLog->created_at->format('Y-m-d');
        $cacheKey = 'user_login_log_' . $clickLog->user_id;
        $login_log_cache = Cache::get($cacheKey);
        if (!empty($login_log_cache)) {
            $statistics_date = $login_log_cache->created_at->format('Y-m-d');
        }
        if ($clickLog->event_type == 'login') {
            StatisticDetail::firstOrCreate(
                [
                    'create_day' => $statistics_date,
                    'type' => 'login',
                    'user_id' => $clickLog->user_id
                ]
            );
            Cache::put($cacheKey, $clickLog, 3600);
            User::where('id', $clickLog->user_id)->increment('login_count');
        } else {
            $data = [
                'create_day' => $statistics_date,
                'type' => $clickLog->event_type,
                'user_id' => $clickLog->user_id,
                'goods_id' => $clickLog->goods_id
            ];
            if ($clickLog->event_type == 'order') {
                $data['pay_way'] = $clickLog->pay_way;
                $data['order_nu'] = $clickLog->order_nu;
                $data['amount'] = $clickLog->amount;
            }
            StatisticDetail::create($data);
        }
    }
}
